package com.monitorRoutine.monitorRoutineServer.clt;

import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@Slf4j
@RestController
@RequestMapping("/file")
@Api(tags = "文件 API")
public class FileController {
    @Value("${configuration.requestsNumber}")
    private int maxRequestsNumber;
    private static final AtomicInteger currentRequests = new AtomicInteger(0);
    private static final Lock lock = new ReentrantLock();

    @Value("${file.savePath}")
    String SAVE_PATH;
    @GetMapping("/download/{fileName}")
    @ApiOperation(value = "文件-下载")
    public ResponseEntity<?> downloadFile(@PathVariable String fileName) throws IOException {
        lock.lock();
        try {
            // 检查当前请求数是否超过最大值
            if (currentRequests.get() >= maxRequestsNumber) {
                throw new IllegalStateException("Maximum number of concurrent downloads exceeded.");
            }
            // 增加当前请求数
            currentRequests.incrementAndGet();
        Path filePath = Paths.get(SAVE_PATH).resolve(fileName).normalize();
        Resource resource = new FileSystemResource(filePath.toFile());

        if (!resource.exists()) {
            throw new FileNotFoundException("File not found: " + fileName);
        }

        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + URLEncoder.encode(resource.getFilename(), "UTF-8") + "\"");
        headers.add(HttpHeaders.CONTENT_TYPE, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(resource.contentLength())
                .body(resource);
        } catch (FileNotFoundException e) {
            return ResponseEntity
                    .notFound()
                    .build();
        }catch (Exception e) {
            return ResponseEntity
                    .status(HttpStatus.TOO_MANY_REQUESTS).body("");
        } finally {
            // 减少当前请求数
            currentRequests.decrementAndGet();
            lock.unlock();
        }
    }
}
